package com.zhiyan.security.account.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhiyan.common.util.model.DataModel;
import com.zhiyan.common.web.SecurityContextHolder;
import com.zhiyan.security.account.domain.entity.Account;
import com.zhiyan.security.account.service.AccountService;
import com.zhiyan.security.account.webservice.rest.AccountRestController;
import com.zhiyan.test.service.TestService;

@Controller
@RequestMapping("/security/account")
public class AccountController {
	private static Logger logger = Logger.getLogger(AccountRestController.class);
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private TestService testService;
	
	//用户管理
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(){
		return "/security/account/index";
	}
	
	//注册页面
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(){
		return "/security/account/register";
	}
	
	//登录页面
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(){
		return "/security/account/login";
	}

    //登出
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public DataModel logout() {
    	DataModel dataModel = new DataModel();
    	try {
			SecurityContextHolder.destroy();	//销毁
			dataModel.setSucc();
			dataModel.setMsg("退出成功");
		} catch (Exception e) {
			dataModel.setFail();
			logger.error(e);
		}
    	return dataModel;
    }
	
	/**
	 * 用户登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public DataModel login(String loginName, String password){
		DataModel dataModel = new DataModel();
		try {
			Account account = accountService.findByLoginName(loginName);
			dataModel.setFail();
			if (account==null || !loginName.equals(account.getLoginName())) {
				String msg = "登录名:"+loginName+", 登录帐号不存在。或没有区分大小写，请检查后再试。";
				dataModel.setMsg(msg);
                logger.error(msg);
			}else if (!password.equals(account.getPassword())) {
				String msg = "用户密码错误或没有区分大小写，请检查后再试。";
				dataModel.setMsg(msg);
                logger.error(msg);
			}else if ("0".equals(account.getIsDelete())) {
				String msg = "登录名:"+loginName+", 帐号被停用,请联系系统管理员。";
				dataModel.setMsg(msg);
                logger.error(msg);
			}else{
				SecurityContextHolder.setUser(account);
				dataModel.setText(account.getName());
				dataModel.setSucc();
				dataModel.setMsg("登录成功");
			}
		} catch (Exception e) {
			dataModel.setFail();
			logger.error(e);
		}
		return dataModel;
	}

	
}
